﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;

namespace SilverlightCalendar
{
    public partial class MainPage : UserControl
    {
        private int currentYear = DateTime.Now.Year;
        private int selectedMonth = DateTime.Now.Month;
        
        private string[] arrMonthList = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
        private string[] arrWeekList = { "S", "M", "T", "W", "T", "F", "S" };
        
        private Color[] arrBackgroundList = { Colors.LightGray, Colors.Blue, Colors.Red, Colors.Cyan, Colors.Magenta, Colors.Orange, Colors.Yellow };

        public MainPage()
        {
            InitializeComponent();
        }

        private void onLoaded(object sender, RoutedEventArgs e)
        {
            
            loadBackgroundList();
            startCalendar();
        }

        void loadBackgroundList()
        {           

            // The width and height for a background select box.
            int backgroundSelectBoxWidth = 20;
            for (int i = 0; i < arrBackgroundList.Length; i++)
            {
                var tempLeft = (backgroundSelectBoxWidth + 2) * i;

                Rectangle rect = new Rectangle();
                rect.Name = "rectColorBox" + i.ToString();
                rect.Cursor = Cursors.Hand;
                rect.Width = backgroundSelectBoxWidth;
                rect.Height = backgroundSelectBoxWidth;


                rect.Stroke = new SolidColorBrush() { Color = Colors.White };

                rect.StrokeThickness = 1;

                rect.Margin = new Thickness(tempLeft, 0, 0, 0);

                rect.Fill = new SolidColorBrush((Color)arrBackgroundList.GetValue(i));// { Color = arrBackgroundList.GetValue(i) as Color };
                //rect.Fill = new SolidColorBrush(getColorFromHexString(arrBackgroundList.GetValue(i).ToString().Replace("#", "")));// { Color = arrBackgroundList.GetValue(i) as Color };


                rect.MouseLeftButtonUp += new MouseButtonEventHandler(selectBackgroundClick);
                rect.MouseEnter += new MouseEventHandler(selectBackgroundMouseOver);
                rect.MouseLeave += new MouseEventHandler(selectBackgroundMouseLeave);

                rect.RadiusX = 32;
                rect.RadiusY = 32;

                TransformGroup tg = new TransformGroup();
                ScaleTransform st = new ScaleTransform();
                st.ScaleX = 1;
                st.ScaleY = 1;
                st.CenterX = backgroundSelectBoxWidth / 2;
                st.CenterY = backgroundSelectBoxWidth / 2;
                tg.Children.Add(st);

                rect.RenderTransform = tg;
                BackgroundSelectContainer.Children.Add(rect);
                                
            }

            // Set the default background color using the first color.
            changeBackground((Color)arrBackgroundList.GetValue(0));
        }

        // Change the background color.
        void changeBackground(Color selectedColor)
        {
            MainBgColorAnimation.To = selectedColor;
            MainBgStoryboard.Begin();
            //glass.Begin();
        }

        void selectBackgroundMouseLeave(object sender, MouseEventArgs e)
        {            
            ColorBoxAnimation2.Stop();
            Storyboard.SetTargetName(ColorBoxAnimation2, ((Rectangle)sender).Name);            
            ColorBoxAnimation2.Begin();
        }

        void selectBackgroundMouseOver(object sender, MouseEventArgs e)
        {            
            ColorBoxAnimation1.Stop();
            Storyboard.SetTargetName(ColorBoxAnimation1, ((Rectangle)sender).Name);            
            ColorBoxAnimation1.Begin();

            Brush scb = ((Rectangle)sender).Fill;
            SolidColorBrush b = scb as SolidColorBrush;
            changeBackground(b.Color);
        }

        void selectBackgroundClick(object sender, MouseButtonEventArgs e)
        {
            Brush scb = ((Rectangle)sender).Fill;
            SolidColorBrush b = scb as SolidColorBrush;
            changeBackground(b.Color);
        }        

        void startCalendar()
        {
            var today = DateTime.Now;
            selectedMonth = today.Month - 1;
            currentYear = today.Year;            
            loadCalendar();            
        }
        
        int GetMalayDay(string day)
        {
            int str = 0;
            switch (day)
            {
                case "sunday": str = 0; break;
                case "monday": str = 1; break;
                case "tuesday": str = 2; break;
                case "wednesday": str = 3; break;
                case "thursday": str = 4; break;
                case "friday": str = 5; break;
                case "saturday": str = 6; break;
            }
            return str;
        }

        void loadCalendar()
        {
            // Get the days count in the selected month.
            var daysInSelectedMonth = DateTime.DaysInMonth(DateTime.Now.Year, selectedMonth + 1);// new Date(currentYear, selectedMonth, 32).getDate();

            DateTime dt = DateTime.Parse("1/" + (selectedMonth + 1).ToString() + "/" + DateTime.Now.Year.ToString());

            int firstDayInWeek = GetMalayDay(dt.DayOfWeek.ToString().ToLower());// DateTime.Now.Day; // new Date(currentYear, selectedMonth, 1).getDay();

            


            // Show calendar month content.            
            ScreenTextBlock.Text = arrMonthList[selectedMonth].ToString() + " " + currentYear.ToString();

            // Show calendar days content.           
            if (CalendarDaysContainer.Children.Count > 0)
            {
                CalendarDaysContainer.Children.Clear();
            }

            int dayTextHeight = 22;
            int dayTextWidth = 402 / 7;
            int tmpDayInWeek = firstDayInWeek;
            int virtualDaysInSelectedMonth = daysInSelectedMonth;
            bool showDaysInOneRow = true;
            int paddingTopWeek = 5;

            // If one row can't display 31 days, will display one week each row.           
            if (CalendarDaysContainer.Width < 685)
            {
                virtualDaysInSelectedMonth += tmpDayInWeek;
                showDaysInOneRow = false;
                tmpDayInWeek = 0;
            }

            Color textColor = Colors.Black;
            // Show week days description.
            for (int i = 1; i <= virtualDaysInSelectedMonth; i++)
            {
                if (showDaysInOneRow == false && i > 7)
                {
                    break;
                }

                textColor = Colors.White;
                if (tmpDayInWeek == 0 || tmpDayInWeek == 6)
                {
                    textColor = Colors.Red;
                }
                
                var paddingLeft = (i - 1) * dayTextWidth;
                               

                // Add week days description.
                if (showDaysInOneRow == true || (showDaysInOneRow == false && i <= 7))
                {
                    TextBlock txt = new TextBlock();
                    txt.FontFamily = new FontFamily("Arial");
                    txt.FontSize = 20;
                    txt.Margin = new Thickness(paddingLeft, paddingTopWeek, 0, 0);
                    txt.Foreground = new SolidColorBrush(textColor);
                    txt.Text = arrWeekList[tmpDayInWeek].ToString();
                                        
                    CalendarDaysContainer.Children.Add(txt);
                }
                if (tmpDayInWeek >= 6)
                    tmpDayInWeek = 0;
                else
                    tmpDayInWeek++;
            }

            // Show days in this month.
            int dayTextRowIndex = 0;
            //int currentDayText = 0;
            if (showDaysInOneRow == false)
                tmpDayInWeek = 0;
            else
                tmpDayInWeek = firstDayInWeek;
            for (int i = 1; i <= virtualDaysInSelectedMonth; i++)
            {
                var paddingLeft = (i - 1) * dayTextWidth;
                if (showDaysInOneRow == false)
                {
                    if (i == 7 * dayTextRowIndex + 1)
                        dayTextRowIndex++;
                    paddingLeft = (i - 1 - 7 * (dayTextRowIndex - 1)) * dayTextWidth;
                }
                else
                {
                    dayTextRowIndex = 1;
                }
                int actualDayText = i;
                if (showDaysInOneRow == false)
                {
                    actualDayText = i - firstDayInWeek;
                    if (actualDayText <= 0)
                        actualDayText = 0;
                }
                textColor = Colors.White;
                if (tmpDayInWeek == 0 || tmpDayInWeek == 6)
                    textColor = Colors.Red;

                var paddingTop = (dayTextHeight + 7) * dayTextRowIndex + paddingTopWeek;
                
                TextBlock txtm = new TextBlock();
                txtm.FontFamily = new FontFamily("Arial");
                txtm.FontSize = 22;
                txtm.Name = "txtDay" + i.ToString();

                txtm.Margin = new Thickness(paddingLeft, paddingTop, 0, 0);
                if(actualDayText == DateTime.Now.Day)
                    txtm.Foreground = new SolidColorBrush(Colors.Yellow);
                else
                    txtm.Foreground = new SolidColorBrush(textColor);

                if(actualDayText == 0)
                    txtm.Text = "";
                else
                    txtm.Text = actualDayText.ToString();


                

                CalendarDaysContainer.Children.Add(txtm);

                if (tmpDayInWeek >= 6)
                    tmpDayInWeek = 0;
                else
                    tmpDayInWeek++;
            }

        }

        
        
        public Color getColorFromHexString(string s)
        {
            byte a = System.Convert.ToByte(s.Substring(0, 2), 16);
            byte r = System.Convert.ToByte(s.Substring(2, 2), 16);
            byte g = System.Convert.ToByte(s.Substring(4, 2), 16);
            byte b = System.Convert.ToByte(s.Substring(6, 2), 16);
            return Color.FromArgb(a, r, g, b);
        }


        

        private void PrevNavButtonClick(object sender, MouseButtonEventArgs e)
        {
            if (selectedMonth == 0)
            {
                selectedMonth = 11;
                currentYear--;
            }
            else
                selectedMonth--;

            loadCalendar();
        }

        private void NextNavButtonClick(object sender, MouseButtonEventArgs e)
        {
            if (selectedMonth == 11)
            {
                selectedMonth = 0;
                currentYear++;
            }
            else
                selectedMonth++;

            loadCalendar();
        }

        
    }
}
